package com.security.sms;
import android.annotation.SuppressLint;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class SmsInboxUtils {
    private static SmsInboxUtils mContactUtils;
    private OnSmsInboxListener mListener;
    public static SmsInboxUtils with() {
        if (mContactUtils == null) {
            synchronized (SmsInboxUtils.class) {
                mContactUtils = new SmsInboxUtils();
            }
        }
        return mContactUtils;
    }
    public void getSms(Context context, OnSmsInboxListener listener) {
        mListener = listener;
        MyAsyncQueryhandler asyncQueryhandler = new MyAsyncQueryhandler(context.getContentResolver());
        Uri uri = Uri.parse("content://sms/");
        String[] projection = new String[]{"address", "person", "body", "date", "type"};
        asyncQueryhandler.startQuery(0, null, uri, projection, null, null, "date desc");
    }
    private String getDate(String date) {
        Date callDate = new Date(Long.parseLong(date));
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(callDate);
    }
    @SuppressLint("HandlerLeak")
    private class MyAsyncQueryhandler extends AsyncQueryHandler {
        public MyAsyncQueryhandler(ContentResolver cr) {
            super(cr);
        }
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            if (cursor != null && cursor.getCount() > 0) {
                List list = new ArrayList<>();
                while (cursor.moveToNext()) {
                    String number = cursor.getString(cursor.getColumnIndex("address"));//手机号
                    String name = cursor.getString(cursor.getColumnIndex("person"));//联系人姓名列表
                    String body = cursor.getString(cursor.getColumnIndex("body"));//内容
                    String date = getDate(cursor.getString(cursor.getColumnIndex("date")));//时间
                    String type = cursor.getString(cursor.getColumnIndex("type"));//1是接收到的，2是已发出
                    list.add(new SMSBean(date, name, number, body, type));
                }
                mListener.onSuccess(list);
            } else {
                if (mListener != null) mListener.onFailed();
            }
            super.onQueryComplete(token, cookie, cursor);
        }
    }
}